/**
 * Created by oneminute on 7/17/14.
 */

var lz = require("../lib/utils/modules")();
var util = require("util");
var moment = require("moment");
var async = require("async");

exports.post = function (_req, _res, _opts, _callback) {
    var loginPhone = lz.Utils.decrypt(_opts.loginPhone);
    var code = _opts.code;
    var password = lz.Utils.decrypt(_opts.password);

    // 先判断手机号是否已经被注册过
    lz.ArangoDB.countObjectsByAQL(lz.Config.db.arango.aqls.GET_OBJECT_BY_PROPERTY, {
        "@collection": lz.Config.db.arango.users,
        prop: "loginPhone",
        value: loginPhone
    }, function (_err, _count) {
        if (_err) {
            lz.Logger.error("/register: 查询手机号是否已经被注册时发生错误。", _err);
            _callback(_err);
            return;
        }

        if (_count > 0) {
            lz.Logger.warn("/register: 该手机号%s已经被注册。", loginPhone);
            _callback(lz.Config.errors.getError(lz.Config.errors.REGISTER_USER_EXISTED));
            return;
        }

        // 再来作手机号是否已发送的验证
        var messageCode = new lz.MessageCode({phone: loginPhone});
        messageCode.list({
            method: "byAQL",
            aql: lz.Config.db.arango.aqls.LIST_MESSAGE_CODE,
            params: {
                "@collection": lz.Config.db.arango.codes,
                phone: loginPhone,
                type: "register"
            }
        }, function (_err, _messages) {
            if (_err) {
                lz.Logger.error("/register: 查询%s的消息码时出现错误。", loginPhone);
                _callback(_err);
                return;
            }
            lz.Logger.debug("/register: 检索当前手机用户%s的验证码返回: ", loginPhone, _messages);
            // 判断是否有_messages，如果有，则判断最近的一条是否已经过期。
            if (Array.isArray(_messages) && _messages.length > 0) {
                var sms = _messages[0];
                // 判断是否在有效期内
                var sentTime = moment(sms.timestamp, lz.Config.datetimeFormatLong);
                var now = moment();
                var expireTime = sentTime.add(moment.duration(lz.Config.sms.expire * 1000));
                // 过期
                if (now.isAfter(expireTime)) {
                    lz.Logger.warn("/register: 验证码过期。");
                    _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_CODE_EXPIRE));
                    return;
                }
                if (sms.code != code) {
                    lz.Logger.warn("/register: 验证码错误。");
                    _callback(lz.Config.errors.getError(lz.Config.erros.REQUEST_SMS_WRONG_CODE));
                    return;
                }
                lz.Logger.debug("/requestcode: 准备删除所有旧的验证码。");
                var tasks = [];
                _messages.forEach(function (_msg) {
                    tasks.push(function (_cb) {
                        _msg.delete(function () {
                            _cb(null);
                        });
                    });
                });
                async.series(tasks, function () {
                    lz.Logger.debug("/requestcode: 已经删除所有旧的验证码。");
                    var user = new lz.User({
                        id: lz.Utils.getUUID("u_"),
                        name: lz.Utils.getRandName("我要"),
                        password: password,
                        loginPhone: loginPhone,
                        phone: loginPhone,
                        inbusiness: true
                    });
                    user.save(function (_err, _user) {
                        if (_err) {
                            lz.Logger.error("/register: 保存用户信息过程中发生错误。", _err);
                            _callback(_err);
                            return
                        }

                        _callback(null, user, {
                            name: user.name,
                            inbusiness: user.inbusiness
                        });
                    });
                });
            } else {
                lz.Logger.warn("/register: 没有发现验证码。");
                _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_NO_CODE));
                return;
            }
        });
    });

};
